import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
import { Form, Spin, Typography, InputNumber, Switch, Button } from 'antd';
import { createGlobalStyle } from 'styled-components';
import { getAllTransitions, updateVideoConfig } from '@/services/project';
import { useSelector, useDispatch } from 'react-redux';
import { selectVideoById, updateVideoProperties } from '@/store/videosSlice'; // 确认路径正确
import type { RootState } from '@/store'; // 确认路径正确
import { CloseCircleOutlined } from '@ant-design/icons';
import { setTransitionStyle } from '@/store/transitionsSlice';

const { Title, Text } = Typography;

// 全局 Ant Design 深色主题样式 (保持不变)
const GlobalAntdDarkThemeStyle = createGlobalStyle`
    /* ... 样式代码保持不变 ... */
    .config-video-transition-scroll::-webkit-scrollbar { width: 3px; background: transparent; }
    .config-video-transition-scroll::-webkit-scrollbar-thumb { background: #715BB8; border-radius: 4px; }
    .ant-form-item-label > label { color: #FFFFFF !important; }
    .ant-input-number, .ant-select-selector {
        background-color: #3C3C3C !important;
        color: #FFFFFF !important;
        border-color: #555555 !important;
    }
    .ant-input-number:hover, .ant-input-number:focus,
    .ant-select:not(.ant-select-disabled):hover .ant-select-selector {
        border-color: #888888 !important;
        box-shadow: 0 0 0 2px rgba(136, 136, 136, 0.2) !important;
    }
    .ant-input-number-handler-wrap { background-color: #3C3C3C !important; }
    .ant-input-number-handler { color: #FFFFFF !important; border-color: #555555 !important; }
    .ant-input-number-disabled, .ant-input-number-disabled:hover {
        background-color: #333333 !important;
        color: #AAAAAA !important;
        cursor: not-allowed;
        border-color: #444444 !important;
    }
    .ant-input-number-disabled .ant-input-number-input {
        background-color: #333333 !important;
        color: #AAAAAA !important;
        cursor: not-allowed;
    }
    .ant-switch { background-color: #555555 !important; }
    .ant-switch-checked { background-color: #715BB8 !important; }
`;

interface ConfigVideoTransitionFormProps {
    videoId: string;
}

const getRandomColor = () => {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
};

const ConfigVideoTransitionForm: React.FC<ConfigVideoTransitionFormProps> = ({ videoId }) => {
    const [form] = Form.useForm();
    const dispatch = useDispatch();
    const video = useSelector((state: RootState) => (videoId ? selectVideoById(state, videoId) : null));
    const [transitionsData, setTransitionsData] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const transitionColors = useRef<{ [key: string]: string }>({});

    useEffect(() => {
        transitionsData.forEach((t) => {
            if (t.name && !transitionColors.current[t.name]) {
                transitionColors.current[t.name] = getRandomColor();
            }
        });
    }, [transitionsData]);

    useEffect(() => {
        setLoading(true);
        getAllTransitions()
            .then((res) => {
                const freeTransitions = res.data?.data?.free || [];
                const vipTransitions = res.data?.data?.vip || [];
                setTransitionsData([...freeTransitions, ...vipTransitions]);
            })
            .catch((error) => console.error('获取转场数据失败:', error))
            .finally(() => setLoading(false));
    }, []);

    // ✅ [关键修复 1]：当 Redux 中的视频数据变化时，精确同步到表单
    useEffect(() => {
        if (video) {
            const transitionType = video.transition?.transition_type;
            const durationStr = video.transition?.duration;

            form.setFieldsValue({
                // 如果是 "None"，在表单中我们用 null 来代表“无”选项
                transition_type: transitionType === 'None' ? null : transitionType,
                // 解析 "1.0s" 这样的字符串为数字 1.0
                duration: durationStr ? parseFloat(durationStr) : 1.0,
            });
        } else {
            form.resetFields();
        }
    }, [video, form]);

    // 专门处理转场类型变化的方法
    const handleTransitionTypeChange = useCallback(
        (transitionType: string | null) => {
            if (!videoId) return;

            // 获取当前持续时间值
            const duration = form.getFieldValue('duration') || 1.0;

            if (transitionType) {
                // 用户选择了一个具体的转场
                dispatch(
                    updateVideoProperties({
                        id: videoId,
                        updates: {
                            transition: {
                                transition_type: transitionType,
                                duration: `${duration.toFixed(1)}s`,
                            },
                        },
                    })
                );
            } else {
                // 用户选择了“无”
                dispatch(
                    updateVideoProperties({
                        id: videoId,
                        updates: {
                            transition: {
                                transition_type: 'None',
                                duration: '0s',
                            },
                        },
                    })
                );
            }
        },
        [videoId, dispatch, form]
    );

    // 专门处理持续时间变化的方法
    const handleDurationChange = useCallback(
        (duration: number) => {
            if (!videoId) return;

            const transitionType = form.getFieldValue('transition_type');
            const randomEnabled = form.getFieldValue('randomTransitionEnabled');

            // 只有在未开启随机转场且选择了具体转场时才更新持续时间
            if (!randomEnabled && transitionType) {
                dispatch(
                    updateVideoProperties({
                        id: videoId,
                        updates: {
                            transition: {
                                transition_type: transitionType,
                                duration: `${duration.toFixed(1)}s`,
                            },
                        },
                    })
                );
            }
        },
        [videoId, dispatch, form]
    );

    const allDisplayTransitions = useMemo(() => [{ name: null, display_name: '无', is_vip: false, is_none: true }, ...transitionsData], [transitionsData]);

    const selectedTransitionType = Form.useWatch('transition_type', form);
    // 持续时间在未选择转场时禁用
    const isDurationDisabled = !selectedTransitionType;

    if (!videoId) {
        return (
            <div
                style={{
                    padding: '20px',
                    color: '#FFFFFF',
                    backgroundColor: '#282828',
                    height: '100%',
                }}
            >
                未选择任何视频片段
            </div>
        );
    }

    return (
        <>
            <GlobalAntdDarkThemeStyle />
            <div
                className="config-video-transition-scroll"
                style={{
                    maxHeight: 540,
                    overflowX: 'hidden',
                    overflowY: 'auto',
                    backgroundColor: '#282828',
                    color: '#FFFFFF',
                    padding: '16px',
                    borderRadius: '8px',
                }}
            >
                <div
                    style={{
                        display: 'flex',
                        gap: '12px',
                        marginBottom: '16px',
                    }}
                >
                    <Button
                        style={{
                            backgroundColor: '#00FF0080',
                            borderColor: '#00FF0080',
                        }}
                        onClick={async () => {
                            // 直接使用组件顶部已经通过useSelector获取的video数据
                            if (video) {
                                try {
                                    await updateVideoConfig(video);
                                    dispatch(
                                        setTransitionStyle({
                                            videoId,
                                            transitionType: video.transition?.transition_type,
                                        })
                                    );
                                    // 可以添加一些保存成功的提示
                                } catch (error) {
                                    console.error('保存视频转场配置失败:', error);
                                }
                            }
                        }}
                    >
                        保存视频转场配置
                    </Button>
                    <Button
                        style={{
                            backgroundColor: '#00FF0080',
                            borderColor: '#00FF0080',
                        }}
                        onClick={() => {
                            if (!videoId || transitionsData.length === 0) return;

                            // 随机选择一个转场
                            const randomIndex = Math.floor(Math.random() * transitionsData.length);
                            const randomTransition = transitionsData[randomIndex];

                            if (randomTransition && randomTransition.name) {
                                // 更新表单和Redux数据
                                handleTransitionTypeChange(randomTransition.name);
                            }
                        }}
                    >
                        随机转场
                    </Button>
                </div>
                <Title level={4} style={{ marginBottom: 16, color: '#FFFFFF' }}>
                    属性面板
                </Title>
                <Title level={5} style={{ marginTop: 0, marginBottom: 8, color: '#FFFFFF' }}>
                    当前选择
                </Title>
                <div
                    style={{
                        backgroundColor: '#3C3C3C',
                        color: '#FFFFFF',
                        padding: '8px 12px',
                        borderRadius: '4px',
                        marginBottom: '24px',
                        border: '1px solid #555555',
                    }}
                >
                    <Text style={{ color: '#FFFFFF' }}>
                        ▶️ {video?.name || '未命名视频'}
                        {/* ✅ [UI 优化]：正确显示当前转场名称 */}
                        {video?.transition?.transition_type && video.transition.transition_type !== 'None' && (
                            <span
                                style={{
                                    marginLeft: '8px',
                                    color: '#00c0ff',
                                }}
                            >
                                🔄 {transitionsData.find((t) => t.name === video.transition.transition_type)?.display_name || video.transition.transition_type}
                            </span>
                        )}
                    </Text>
                </div>
                <Title level={5} style={{ color: '#FFFFFF', marginTop: 0 }}>
                    转场效果
                </Title>
                <Form form={form} layout="vertical" initialValues={{ duration: 1.0, transition_type: null }} preserve={false}>
                    <Form.Item name="transition_type" hidden>
                        <input />
                    </Form.Item>

                    <Form.Item label="持续时间 (秒)" name="duration" style={{ marginBottom: 24 }}>
                        <InputNumber min={0.1} max={10} step={0.1} style={{ width: '100%' }} addonAfter="s" disabled={isDurationDisabled} onChange={() => handleDurationChange} />
                    </Form.Item>
                    <Spin spinning={loading}>
                        <div
                            style={{
                                display: 'grid',
                                gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))',
                                gap: '12px',
                            }}
                        >
                            {allDisplayTransitions.map((transition) => {
                                const isSelected = selectedTransitionType === transition.name;
                                const previewBackgroundColor = transition.is_none ? '#4A4A4A' : transitionColors.current[transition.name] || '#ccc';
                                return (
                                    <div
                                        key={transition.name || `none-transition`}
                                        onClick={() => {
                                            handleTransitionTypeChange(transition.name);
                                        }}
                                        style={{
                                            cursor: 'pointer',
                                            opacity: 1,
                                            border: isSelected ? '2px solid #FF7F00' : '2px solid transparent',
                                            borderRadius: '4px',
                                            padding: '8px',
                                            textAlign: 'center',
                                            backgroundColor: '#3C3C3C',
                                            transition: 'all 0.2s ease',
                                            display: 'flex',
                                            flexDirection: 'column',
                                            alignItems: 'center',
                                            justifyContent: 'space-between',
                                            minHeight: '140px',
                                            boxShadow: isSelected ? '0 0 8px rgba(255, 127, 0, 0.5)' : 'none',
                                        }}
                                    >
                                        <div
                                            style={{
                                                width: '100%',
                                                paddingTop: '56.25%',
                                                backgroundColor: previewBackgroundColor,
                                                borderRadius: '2px',
                                                marginBottom: '8px',
                                                display: 'flex',
                                                justifyContent: 'center',
                                                alignItems: 'center',
                                                position: 'relative',
                                                overflow: 'hidden',
                                                flexShrink: 0,
                                            }}
                                        >
                                            {transition.is_none ? (
                                                <CloseCircleOutlined
                                                    style={{
                                                        fontSize: '36px',
                                                        color: '#999',
                                                    }}
                                                />
                                            ) : null}
                                        </div>
                                        <div
                                            style={{
                                                fontSize: '13px',
                                                color: '#e0e0e0',
                                                whiteSpace: 'nowrap',
                                                overflow: 'hidden',
                                                textOverflow: 'ellipsis',
                                                width: '100%',
                                                marginTop: 'auto',
                                            }}
                                        >
                                            {transition.display_name}
                                            {transition.is_vip ? ' (VIP)' : ''}
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    </Spin>
                </Form>
            </div>
        </>
    );
};

export default ConfigVideoTransitionForm;
